<?php
namespace Common\Action;
use Common\Action\FuncAction;
/**
 * 前台控制器基类
 */
class TopAction extends FuncAction
{

protected function _initialize()
{

if (false === ($setting = F('setting'))) {
    $setting = D('setting')->setting_cache();
}	
C($setting);
$this->params=I('param.');
$Now=NOW_TIME;
		
    }
    
   	protected function Fstatic($id){
		switch($id){
			case 2 :
			return '待付款';
			break;
			case 1 :
			return '已付款';
			break;
			default : 
			return '异常';
			break;
		}

	}
   
    
    public function _empty()
    {
        $this->_404();
    }
	
protected function check_verify($code, $id = ''){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

Public  function verify(){
ob_end_clean();
$Verify =    new \Think\Verify();
$Verify->fontSize = 30;
$Verify->length   = 4;
$Verify->useCurve = false;
$Verify->useNoise = false;
$Verify->entry();
}


protected function bindorder(){
$mod=M('order');		
$stime = strtotime("-10 day");
$sql ='select a.oid,a.fuid,a.guid,a.id as uid,b.id from tqk_user as a LEFT JOIN tqk_order as b ON a.oid=b.oid where b.uid=0 and b.nstatus=1 and b.add_time>'.$stime;
$Model = M();
$list_child=$Model->cache(true, 5 * 60)->query($sql);
foreach($list_child as $k=>$v){
$data=array(
'uid'=>$v['uid'],
'fuid'=>$v['fuid'],
'guid'=>$v['guid'],
);
$map=array(
'id'=>$v['id']
);
$mo=$mod->where($map)->save($data);

}
 



}



protected function randStr($uid,$len = 6, $format = 'ALL')
{
    switch ($format) {
        case 'ALL':
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        break;
        case 'CHAR':
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        break;
        case 'HIGHER':
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        break;
        case 'LOWER':
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        break;
        case 'NUMBER':
        $chars = '0123456789';
        break;
        default:
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
        break;
    }
    mt_srand((double) microtime() * 1000000 * $uid);
    $password = "";
    while (strlen($password) < $len)
        $password .= substr($chars, (mt_rand() % strlen($chars)), 1);
    
    return $password;
}

 protected function _curl($url, $data = array(), $is_post = false, $cookie = null, $referer = null)
    {
        set_time_limit(30);
        $curl = curl_init();
        if($data && $is_post == false){
            $url .= '?' . http_build_query($data);
        }
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //
		curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //
		curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($is_post){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        if($cookie){
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
       curl_setopt($curl, CURLOPT_REFERER, C('yh_site_url'));
       curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090730 Firefox/3.5.2 GTB5' );  
        curl_setopt($curl, CURLOPT_TIMEOUT,30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
       curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        $result = curl_exec($curl);
		//var_dump(curl_error($curl));
        curl_close($curl);
        if (empty($result)) {
            $result = false;
        }
        
        return $result;
    }


protected function check_token($key){
$token=$this->params['token'];
if(!isset($token) || empty($token)){
exit($this->return_json('401','Token不能为空'));
}
$apptoken=$this->params['token'];
$result=$this->params;
unset($result['token']);
$ServerToken='';
foreach($result as $k=>$v){
	$ServerToken.=md5($v);
}
$ServerToken=md5($ServerToken .'_'.$key);
if($apptoken!=$ServerToken){
$this->header_403();	
exit($this->return_json('403','无效的Token',$result));
}
}

protected function check_tb_token($key){
$token=$this->params['token'];
if(!isset($token) || empty($token)){
exit($this->return_json('401','Token不能为空'));
}
$apptoken=$this->params['token'];
$result = array();
$result['uid']=$this->params['uid'];
$result['from']=$this->params['from'];
$ServerToken='';
foreach($result as $k=>$v){
	$ServerToken.=md5($v);
}
$ServerToken=md5($ServerToken .'_'.$key);
if($apptoken!=$ServerToken){
$this->header_403();	
exit($this->return_json('403','无效的Token',$result));
}
}


protected function create_token($key,$data=array()){
$ServerToken='';
foreach($data as $k=>$v){
	$ServerToken.=md5($v);
}
$ServerToken=md5($ServerToken .'_'.$key);
return $ServerToken;
}	


protected function delorder(){
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/runtime/Data/history/delorder.php';
$ret=opcache_invalidate($dir,TRUE);
}
 $delorder = F('history/delorder');
 $NowTimes=NOW_TIME;
if(($NowTimes-$delorder)>600){
$updata=array(
'status'=>2
);
$mod_order=M('order');
$lasttime = mktime(0, 0, 0, date("m"), date("d")-20, date("Y"));
$upwhere['status']=1;
$upwhere['add_time'] = array('lt',$lasttime);
$res=$mod_order->where($upwhere)->save($updata);
F('history/delorder', $NowTimes);


}
}	
	

protected function return_json($code,$msg='',$data=''){
	$json=array(
	'status'=>$code,
	'msg'=>$msg,
	'result'=>$data,
	);
     return json_encode($json);	
}

protected function header_403(){
header('HTTP/1.1 403 Forbidden');  	
}
protected function check_time($time){
if($time<=1){
$this->header_403();
exit($this->return_json('403','时间校验异常'));
}
if(abs(time()-$time)>60){
$this->header_403();
exit($this->return_json('403','服务器时间异常'));
}
}

/**
     * 图片上传处理
     * @param [String] $path [保存文件夹名称]
     * @param [String] $thumbWidth [缩略图宽度]
     * @param [String] $thumbHeight [缩略图高度]
     * @return [Array] [图片上传信息]
     */
        
protected function _upload($FILES,$path,$thumb=array()) {
        $obj = new \Think\Upload();// 实例化上传类
        $obj->maxSize = C('yh_attr_allow_size')*1024*1024 ;// 设置附件上传大小
        $obj->savePath =C('yh_attach_path').$path.'/'; // 设置附件上传目录
        $obj->exts = explode(',',C('yh_attr_allow_exts'));// 设置附件上传类型
        $obj->saveName = array('uniqid','');//文件名规则
        $obj->rootPath =ROOT_PATH.'/';
        $obj->replace = true;//存在同名文件覆盖
        $obj->autoSub = true;//使用子目录保存
        $obj->subName  = array('date','Ym');//子目录创建规则，
        $info = $obj->uploadOne($FILES);
        if(!$info) {
            return array('error' =>0, 'info'=> $obj->getError() );
        }else{
            if($thumb){  //生成缩略图
                $image = new \Think\Image();
                    $thumb_file =ROOT_PATH.'/'.$info['savepath'] . $info['savename'];
                    $save_path =ROOT_PATH.'/'.$info['savepath'] . 'thumb_' . $info['savename'];
				    $image->open( $thumb_file )->thumb( $thumb['width'], $thumb['height'],\Think\Image::IMAGE_THUMB_FILLED )->save( $save_path );
				    @unlink($thumb_file); //上传生成缩略图以后删除源文件
				    
				    return array(
                            'status' => 1,
                            'savepath' => $info['savepath'],
                            'savename' => $info['savename'],
                            'pic_path' => $info['savepath'] . $info['savename'],
                            'mini_pic' => '/'.$info['savepath'] . 'thumb_' .$info['savename']
                   );
            }else{
            	
             //   foreach($info as $file) {
                    return array(
                            'status' => 1,
                            'savepath' => $info['savepath'],
                            'savename' => $info['savename'],
                            'pic_path' => '/'.$info['savepath'].$info['savename']
                    );
               // }

            }
        }
    }
	
protected function getthemonth($date){
    $firstday = date('Y-m-01', $date);
    $lastday = date("Y-m-d", strtotime("first day of next month", $date));
    return array(strtotime($firstday),strtotime($lastday));
}
	
    protected function _404($url = '')
    {
        if ($url) {
            redirect($url);
        } else {
            $this->display('Index/404');
            send_http_status(404);
            exit;
        }
    }
    public function getItem($num_iid,$activityId){
 	$appkey = trim(C('yh_taobao_appkey'));
    	$appsecret = trim(C('yh_taobao_appsecret'));
    	if (! empty($appkey) && ! empty($appsecret) && !empty($num_iid)) {
    		vendor('taobao.taobao');
    		$c = new \TopClient();
    		$c->appkey = $appkey;
    		$c->secretKey = $appsecret;
    		$req = new \TbkItemInfoGetRequest();
    		$req->setFields("num_iid,user_type,title,seller_id,volume,nick,pict_url,reserve_price,zk_final_price,item_url");
    		$req->setPlatform("1");
    		$req->setNumIids($num_iid);
    		$resp = $c->execute($req);
    		$resparr = xmlToArray($resp);
    		$contents = $resparr['results']['n_tbk_item'];
		}

        if ($contents) {
			$info = array();
			$info['title'] = $contents['title'];
			$info['volume'] = $contents['volume'];
			$info['price'] = $contents['zk_final_price'];
			$info['pic_url'] = $contents['pict_url'];
			$info['pic_url'] = str_replace('_320x320.jpg', "", $info['pic_url']);
			$info['sellerId'] = $contents['seller_id'];
			$info['nick'] = $contents['nick'];
            if ($contents['user_type'] == "1") {
                $info['shop_type'] = "B";
            } else {
                $info['shop_type'] = "C";
            }
			$info['num_iid'] = $num_iid;
            $info['coupon_start_time'] = date('Y-m-d H:i', time());
            $info['coupon_end_time'] = date('Y-m-d H:i', time() + 86400 * 7);
			$descUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $num_iid . '%22%7D';
            $source = $this->_curl($descUrl);
            if (!$source) {
                $source = file_get_contents($descUrl);
            }
            $result_data = json_decode($source, true);
            $dinfo = array();
            $num = $result_data['data']['images'];
            for ($i = 0; $i < count($num); $i++) {
                $images = $i + 1;
                $desc[$images] = $num[$i];
                $desc[$images] = '<img class="lazy" src=' . $desc[$images] . '>';
            }
            $info['desc'] = $desc[1] . '' . $desc[2] . '' . $desc[3] . '' . $desc[4] . '' . $desc[5] . '' . $desc[6] . '' . $desc[7] . '' . $desc[8] . '' . $desc[9] . '' . $desc[10] . '' . $desc[11] . '' . $desc[12] . '' . $desc[13] . '' . $desc[14] . '' . $desc[15] . '' . $desc[16] . '' . $desc[17] . '' . $desc[18] . '' . $desc[19] . '' . $desc[20] . '' . $desc[21] . '' . $desc[22] . '' . $desc[23] . '' . $desc[24] . '' . $desc[25] . '' . $desc[26] . '' . $desc[27] . '' . $desc[28] . '' . $desc[29] . '' . $desc[30];
			
            return $info;
        } else {
            return false;
        }
    }
    public function http($url)
    {
        set_time_limit(0);
        $result = file_get_contents($url);
        if ($result === false) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);
            curl_close($curl);
        }
        if (empty($result)) {
            $result = false;
        }
        return $result;
    }
    public function get_id($url)
    {
        $id = 0;
        $parse = parse_url($url);
        if (isset($parse['query'])) {
            parse_str($parse['query'], $params);
            if (isset($params['id'])) {
                $id = $params['id'];
            } elseif (isset($params['item_id'])) {
                $id = $params['item_id'];
            } elseif (isset($params['default_item_id'])) {
                $id = $params['default_item_id'];
            } elseif (isset($params['amp;id'])) {
                $id = $params['amp;id'];
            } elseif (isset($params['amp;item_id'])) {
                $id = $params['amp;item_id'];
            } elseif (isset($params['amp;default_item_id'])) {
                $id = $params['amp;default_item_id'];
            }
        }
        return $id;
    }
	
	
protected function getRobot(){
if(empty($_SERVER['HTTP_USER_AGENT']))
 {
  return false;
 }
 $searchEngineBot = array(
  'Googlebot'=>'google',
  'mediapartners-google'=>'google',
  'baiduspider'=>'baidu',
  'msnbot'=>'msn',
  'dotbot'=>'dotbot',
  'youdaobot'=>'yodao',
  'yahoo! slurp'=>'yahoo',
  'yahoo! slurp china'=>'yahoo',
  'iaskspider'=>'iask',
  'sogou web spider'=>'sogou',
  'sogou push spider'=>'sogou',
  'sosospider'=>'soso',
  'bingbot'=>'bing',
  'yandexbot'=>'yan',
  'ahrefsbot'=>'ahrefs',
  '360Spider'=>'360',
  'sitemapx'=>'sitemapx',
  'spider'=>'other',
  'alibaba.security'=>'alibaba',
  'bot'=>'bot',
  'dotbot'=>'dotbot',
  'MJ12bot'=>'MJ12bot',
  'DeuSu'=>'DeuSu',
  'Swiftbot'=>'Swiftbot',
  'YandexBot'=>'YandexBot',
  'YisouSpider'=>'YisouSpider',
  'jikeSpider'=>'jikeSpider',
  'EasouSpider'=>'EasouSpider',
  'oBot'=>'oBot',
  'Sogou'=>'Sogou',
  'semrush'=>'semrush',
  'FlightDeckReports Bot'=>'FlightDeckReports',
  'crawler'=>'other',
 );
 $spider = strtolower($_SERVER['HTTP_USER_AGENT']);
 foreach ($searchEngineBot as $key => $value)
 { 
  if (strpos($spider, $key)!== false)
  {
   return $value;
  }
 }
 return false;
}
    
    /*
	 * 验证是否存在openid
	 */
	protected function verificat(){
		$openid = $_SESSION['user']['openid'];
		$json=array(                                 
			'status'=>'out',                             
			'msg'=>'登录超时'                                
		);  
	  	if(!$openid){
	  		exit(json_encode($json));
	  	}
	}  
     
}